package com.lcm.openapi.resolver;

import com.github.mustachejava.resolver.ClasspathResolver;
import com.lcm.openapi.common.exception.ServiceException;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

public class ClassPathResolver implements DataSourceResolver {

    @Override
    public Reader getReader(String resource) {
        ClassLoader ccl = Thread.currentThread().getContextClassLoader();
        InputStream is = ccl.getResourceAsStream(resource);
        if (is == null) {
            ClassLoader classLoader = ClasspathResolver.class.getClassLoader();
            is = classLoader.getResourceAsStream(resource);
        }
        if(Objects.isNull(is)){
            throw new ServiceException("资源文件不存在或读取失败");
        }
        return new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
    }

}
